package com.tulele.vtool.task.async;

import com.alibaba.fastjson.JSONObject;
import com.tulele.vtool.bus.mapper.log.PushDetailLogMapper;
import com.tulele.vtool.bus.model.DailyPaperInfo;
import com.tulele.vtool.bus.model.UserInfo;
import com.tulele.vtool.bus.model.log.PushDetailLog;
import com.tulele.vtool.bus.model.thirdparty.WxNotifyMsgSetInfo;
import com.tulele.vtool.bus.model.thirdparty.WxPushUserInfo;
import com.tulele.vtool.bus.service.IArticleService;
import com.tulele.vtool.bus.service.IUserService;
import com.tulele.vtool.bus.service.SysGzhService;
import com.tulele.vtool.model.PlatformSysInfo;
import com.tulele.vtool.util.DateUtil;
import com.tulele.vtool.util.RedisCacheUtil;
import com.tulele.vtool.util.SpringContextUtil;
import com.tulele.vtool.wechat.service.WeixinService;
import com.tulele.vtool.wechat.service.WeixinServiceDL;
import com.tulele.vtool.wechat.service.WeixinServiceMap;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;

//18:20 日报推送
@Component
@Slf4j
public class DailyPaperTempMsgAsyncTask {

    @Autowired
    private ObjectFactory<WeixinServiceDL> objectFactory;

    @Autowired
    private SysGzhService sysGzhService;

    @Autowired
    private IUserService userService;

//    @Value("${customerMenuUrl}")
//    private String customerMenuUrl;
//
//    @Value("${cailyPaperTempID}")
//    private String cailyPaperTempID;
//
//    @Value("${articleListMenuUrl}")
//    private String articleListMenuUrl;

    @Autowired
    private PushDetailLogMapper pushDetailLogMapper;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    //20200401 hyl 改成同步发 因为多线程 数据库顶不住
    //20200512 调整参数，多线程跑
    //20200514 日报人数多，不跑多线程
    //@Async("taskExecutor")
    public Integer execute(String openId, Integer headId,String profile) {

        Integer ret = 2;

        UserInfo user = userService.getUserByOpenId(openId, profile);

        if (user != null) {

            WxNotifyMsgSetInfo wxNotifyMsgSetInfo = userService.getUserWxMsgAcceptSwitchInfo(user.getUserId());

            int dailyDataReportAcceptStatus = Optional.ofNullable(wxNotifyMsgSetInfo.getDailyDataReportAcceptStatus()).orElse(1);

            if (dailyDataReportAcceptStatus == 1) {

                SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String lastActiveTime = f.format(user.getLastActiveTime());
                int hours = DateUtil.getTimeDiff(3, lastActiveTime);

                if (hours>=30) {
                    PlatformSysInfo sysGzh = sysGzhService.getPlatformSysInfo(profile);
                    // 发送模板消息接口
                    WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                            // 接收者openid
                            .toUser(user.getOpenId())
                            // 模板id
                            .templateId(sysGzh.getSysGzh().getCailyPaperTempId())
                            // 模板跳转链接
                            .url(sysGzh.getArticleListMenuUrl())
                            .build();

                    DailyPaperInfo dailyPaperInfo = userService.getUserDailyPaper(user.getUserId());

                    if (dailyPaperInfo != null) {
                        String firstMsg = "您的数据日报\n\n退订日报请回复：86";
                        String remarkMsg = "今天您没有发文章和视频\t\uD83D\uDC94\n\n" +
                                "回复数字【 1 】查看潜在客户";
//                                "\t\t\t\t\t\t\uD83D\uDC47\uD83D\uDC47\uD83D\uDC47";
//                                "每天分享朋友圈是最高效，成本最低的拓客方法！\n\n" +
//                                "【" + dailyPaperInfo.getBrandName() + "】伙伴都在分享好文\n\n加油\uD83D\uDCAA\n\n" +
//                                "\uD83D\uDC49回复数字【1】查看您的客户动态\n\n" +
//                                "\uD83D\uDC49回复数字【7】继续为您最新爆文\n\n" +
//                                "\uD83D\uDC49回复数字【9】查看今日最新品牌素材";


                        // 添加模板数据
                        templateMessage.addData(new WxMpTemplateData("first", firstMsg, "#FF00FF"))
                                .addData(new WxMpTemplateData("keyword1", dailyPaperInfo.getSubTotal().toString(), "#A9A9A9"))
                                .addData(new WxMpTemplateData("keyword2", "0", "#A9A9A9"))
                                .addData(new WxMpTemplateData("keyword3", "0", "#A9A9A9"))
                                .addData(new WxMpTemplateData("remark", remarkMsg, "#0000FF"));

                        PushDetailLog pushDetailLog = new PushDetailLog();
                        pushDetailLog.setGzhCode(profile);
                        pushDetailLog.setUserId(user.getUserId());
                        pushDetailLog.setMsgType(9);//日报
                        pushDetailLog.setPushTime(new Date());
                        pushDetailLog.setHeadId(headId);
                        pushDetailLog.setOpenId(user.getOpenId());

                        try {
                            // 发送模板消息
                            WeixinServiceDL weixinService= WeixinServiceMap.getWeixinService(profile);
                            if(weixinService==null) {
                                weixinService = objectFactory.getObject();
                                weixinService.reSetConfigStorage(profile);
                                WeixinServiceMap.putWeixinService(profile,weixinService);
                            }
                            weixinService.getTemplateMsgService().sendTemplateMsg(templateMessage);
                            ret = 0;
                            pushDetailLog.setMsg("成功");
                        } catch (WxErrorException e) {
                            ret = 2;
                            pushDetailLog.setMsg(e.getMessage());
                        }

                        pushDetailLog.setResult(ret);

                        pushDetailLogMapper.addPushDetailLog(pushDetailLog);
                    }
                }
            }
        }
        return ret;
    }
}
